package com.ugoodtech.mdcc.client;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Stone Shaw, 15/11/20
 */


import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.security.LoginFailureHandler;
import com.ugoodtech.mdcc.client.security.LoginSuccessHandler;
import com.ugoodtech.mdcc.client.service.AliSmsProvider;
import com.ugoodtech.mdcc.client.service.ComplaintReportService;
import com.ugoodtech.mdcc.client.service.ComplaintUserService;
import com.ugoodtech.mdcc.client.service.CustomerReportService;
import com.ugoodtech.mdcc.client.service.impl.ComplaintReportAuditServiceImpl;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.AdminUserVo;
import com.ugoodtech.mdcc.core.dto.ComplaintTimeResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.ComplaintTimeService;
import com.ugoodtech.mdcc.core.service.GetDepartmentNameForSendService;
import com.ugoodtech.mdcc.core.service.UserAdminService;
import com.ugoodtech.mdcc.core.service.WechatService;
import com.ugoodtech.mdcc.core.utils.ExceptionUtil;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Configuration
@EnableScheduling // 启用定时任务
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    UserRepository clientUserRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private ServiceReportRecorderRepository serviceReportRecorderRepository;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private AutoMessageTimeRepository autoMessageTimeRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ComplaintReportRepository complaintReportRepository;

    @Autowired
    private ComplaintReportLogRepository complaintReportLogRepository;

    @Autowired
    private TimeOutErrorMsgRepository timeOutErrorMsgRepository;

    @Autowired
    private ComplaintSolutionReportRepository complaintSolutionReportRepository;

    @Autowired
    private ComplaintSolutionTimeOutRepository complaintSolutionTimeOutRepository;

    @Autowired
    private ComplaintUserService complaintUserService;

    @Autowired
    private ComplaintUserRepository complaintUserRepository;

    @Autowired
    private ComplaintReportService complaintReportService;

    @Autowired
    private ComplaintTimeService complaintTimeService;

    @Autowired
    private UserAdminService userAdminService;

    @Autowired
    private GetDepartmentNameForSendService getDepartmentNameForSendService;

    @Value("${alipay.partner}")
    private String partner;

    @Value("${alipay.ali_public_key}")
    private String ali_public_key;

    @Value("${alipay.public_key}")
    private String public_key;

    @Value("${alipay.key}")
    private String alipay_key;

    @Value("${alipay.log_path}")
    private String log_path;

    @Value("${alipay.notify_url}")
    private String notify_url;

    @Value("${alipay.return_url}")
    private String return_url;

    @Value("${alipay.show_url}")
    private String show_url;

    @Value("${alipay.seller_email}")
    private String seller_email;

    @Value("${alipay.buyer_email}")
    private String buyer_email;

    @Value("${alipay.payment_type}")
    private String payment_type;

    @Value("${alipay.input_charset}")
    private String input_charset;

    @Value("${alipay.sign_type}")
    private String sign_type;

    @Autowired
    private CustomerReportService customerReportService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    //    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        //add by tom 去掉spring 4.0crf验证
//        http.csrf().disable();
//    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests()
                .antMatchers("/", "/login", "/main", "/getValidationCode**", "/scripts/**", "/images/**").permitAll()
                //                .antMatchers("/need_authenticated_url/**").authenticated()
                .and()
                .formLogin().loginPage("/login")
                .successHandler(new LoginSuccessHandler())
                .failureHandler(new LoginFailureHandler())
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
                .deleteCookies("remember-me")
                .permitAll()
                .and()
                .csrf()
                .disable()
                .headers().frameOptions().sameOrigin();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //    @Scheduled(cron = "0/20 * * * * ?") // 每20秒执行一次
//    @Scheduled(cron = "30 51 9 * * ?") // 每天9点51分30秒触发任务
//    @Scheduled(cron = "30 * * * * ?") //每天1点0分0秒触发任务
//    @Scheduled(cron = "0 1 0 * * ?") //每天1点0分0秒触发任务
    public void scheduler() {
        logger.warn(">>>>>>>>>>>>> scheduled start<<<<<<<<<<<<<<< ");

        logger.warn(">>>>>>>>>>>>> scheduled end<<<<<<<<<<<<<<< ");
    }

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);

    @Scheduled(cron = "0 0 * * * ?")//每个小时执行一次
    public void pushUserMsg_WeChat() {
        Date date = new Date();
        Long nowTime = date.getTime();
        Date createTime = null;
        Long createTimeLong = null;
        logger.info("当前时间:" + simpleDateFormat.format(date));
        logger.info("开始查询没有填写满意度的报告");
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.customerReport.isNull());
//        builder.and(qCustomerRegularReport.creationTime.before(date));
        builder.and(qCustomerRegularReport.type.eq(false));
        builder.and(qCustomerRegularReport.sended.eq(false));
        List<CustomerRegularReport> customerRegularReportList = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builder);
        for (CustomerRegularReport customerRegularReport : customerRegularReportList) {
            createTime = customerRegularReport.getCreationTime();
            createTimeLong = createTime.getTime();
            if (nowTime - createTimeLong >= 3600000 * 24) {
                //获得服务人员的姓名
                StationReport serviceReport = customerRegularReport.getRegularReport();
                String serviceTypeId = serviceReport.getServiceTypAnswerIds();
                StringBuffer service = new StringBuffer("");
                if (StringUtils.isNotEmpty(serviceTypeId)) {
                    String[] id = serviceTypeId.split(",");
                    for (String str : id) {
                        if (StringUtils.isNotEmpty(str)) {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(str));
                            if (Objects.equals(answerOption.getId(), 191L)) {
                                service = new StringBuffer("漆星服务");
                                break;
                            }
                            service.append(answerOption.getName() + "、");
                        }
                    }
                }
                User serviceUser = serviceReport.getUser();
                UserProfile serviceUserProfile = userProfileRepository.findByUserId(serviceUser.getId());
                String serviceName = serviceUserProfile.getRealName();
                //获得服务人员的手机号
                String serviceTelephone = serviceReport.getContactUser();
                //获得客户的姓名
                String customerName = "";
                try {
                    customerName = customerRegularReport.getRegularReport().getStation().getName();
                } catch (Exception e) {
                }
                //获得维修站的名称
                String stationName = "客户站点";
                try {
                    Station customerStation = stationRepository.findOne(serviceReport.getStation().getId());
                    stationName = customerStation.getName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                logger.info("发送的号码为：" + serviceTelephone);
                logger.info("服务人员名称为：" + serviceName);
                logger.info("维修站为：" + stationName);
                logger.info("客户名称为：" + customerName);
                logger.info("服务项目为：" + service);
                try {
                    logger.info("开始发送短信!");
                    String serviceStr = service.toString();
                    if (!serviceStr.equals("漆星服务")) {
                        serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
                    }
                    SendSmsResponse sendSmsResponse = aliSmsProvider.sendMsg(serviceTelephone, serviceName, customerName,
                            stationName, serviceStr);
                        customerRegularReport.setSended(true);
                        logger.info("短信发送成功");

                    customerRegularReportRepository.save(customerRegularReport);
                    logger.info("开始推送微信");
                    String firstData = "您好，您有一份在" + stationName + "进行的" + service + "的常规服务报告。";
                    wechatService.pushWechatMessage(serviceUser, "jUjiQshE94Fr5PhYigl0aLU_OZeybefechS7Oz1v4x4", Constants.WECHAT_PUSH_URL, firstData,
                            "可登录漆星服务系统进行查看", "客户超过24小时未打分", customerName, customerRegularReport.getUpdateTimeStr(), "", "");
                    logger.info("微信推送成功!");
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("发送失败!");
                }
            }
        }
    }

    @Autowired
    private ReportRedDotRepository reportRedDotRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Scheduled(cron = "0 * * * * ?")//每个小时执行一次
    public void pushServiceMsg_WeChat() {
        Date date = new Date();
        Long nowTime = date.getTime();
        Date updateTime = null;
        Long updateTimeLong = null;
        logger.info("当前时间:" + simpleDateFormat.format(date));
        logger.info("开始查询还没有进行处理的报告");
        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.isSendMsg.eq(0));
//        builder.and(qReportRedDot.creationTime.before(date));
        List<ReportRedDot> reportRedDotList = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
        Map<Long, ReportRedDot> longReportRedDotMap = new HashMap<>();
        for (ReportRedDot redDot : reportRedDotList) {
            updateTime = redDot.getUpdateTime();
            updateTimeLong = updateTime.getTime();
            if (nowTime - updateTimeLong >= 3600000 * 24) {
                longReportRedDotMap.put(redDot.getStationReport().getId(), redDot);
            }
        }
        for (Map.Entry<Long, ReportRedDot> reportId : longReportRedDotMap.entrySet()) {
            ReportRedDot redDot = reportId.getValue();
            User user = redDot.getStationReport().getUser();
            UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
            String realName = "";
            if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                realName = userProfile.getRealName();
            }
            Station station = redDot.getStationReport().getStation();
            String stationName = "";
            if (station != null && StringUtils.isNotEmpty(station.getName())) {
                stationName = station.getName();
            }
            StationReport stationReport = redDot.getStationReport();
            StringBuffer stringBuffer = new StringBuffer("");
            if (stationReport != null && StringUtils.isNotEmpty(stationReport.getServiceTypAnswerIds())) {
                String[] ids = stationReport.getServiceTypAnswerIds().split(",");
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        if (id.equals("191")) {
                            stringBuffer.append("漆星服务");
                            break;
                        } else {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                            if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                stringBuffer.append(answerOption.getName() + ",");
                            }
                        }
                    }
                }
            }
            StringBuffer departBuffer = new StringBuffer("");
            StringBuffer userBuffer = new StringBuffer("");
            Map<User, Integer> telephoneUser = new HashMap<>();
            if (stationReport != null && StringUtils.isNotEmpty(stationReport.getDeparmentIds())) {
                String[] ids = stationReport.getDeparmentIds().split(",");
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        Department department = departmentRepository.findOne(Long.valueOf(id));
                        if (department != null && StringUtils.isNotEmpty(department.getName())) {
                            QServiceReportRecorder qServiceReportRecorder = QServiceReportRecorder.serviceReportRecorder;
                            BooleanBuilder booleanBuilder = new BooleanBuilder();
                            booleanBuilder.and(qServiceReportRecorder.deleted.eq(false));
                            booleanBuilder.and(qServiceReportRecorder.enabled.eq(true));
                            booleanBuilder.and(qServiceReportRecorder.stationReport.id.eq(stationReport.getId()));
                            booleanBuilder.and(qServiceReportRecorder.department.id.eq(department.getId()));
                            booleanBuilder.and(qServiceReportRecorder.user.isNull());
                            List<ServiceReportRecorder> reportRecorderList = (List<ServiceReportRecorder>) serviceReportRecorderRepository.findAll(booleanBuilder);
                            if (reportRecorderList != null || reportRecorderList.size() > 0) {
                                departBuffer.append(department.getName() + ",");
                            } else {
                                continue;
                            }
                        }
                        QUserProfile qUserProfile = QUserProfile.userProfile;
                        builder = new BooleanBuilder();
                        builder.and(qUserProfile.deleted.eq(false));
                        builder.and(qUserProfile.enabled.eq(true));
                        builder.and(qUserProfile.departmentList.any().id.eq(Long.valueOf(id)));
                        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
                        for (UserProfile profile : userProfileList) {
                            userBuffer.append(profile.getTelephone() + ",");
                            telephoneUser.put(profile.getUser(), 1);
                        }
                    }
                }
            }
            logger.info("发送的号码为：" + userBuffer);
            logger.info("服务人员名称为：" + realName);
            logger.info("维修站为：" + stationName);
            logger.info("服务项目为：" + stringBuffer);
            logger.info("部门为：" + departBuffer);
            try {
                String serviceStr = stringBuffer.toString();
                if (!serviceStr.equals("漆星服务")) {
                    serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
                }
                String departmentStr = "";
                if (StringUtils.isNotEmpty(departBuffer.toString())) {
                    departmentStr = departBuffer.toString().substring(0, departBuffer.toString().length() - 1);
                }
                aliSmsProvider.sendMsg_24(userBuffer.toString(), realName, stationName,
                        serviceStr, departmentStr);
                redDot.setIsSendMsg(1);
                reportRedDotRepository.save(redDot);
                logger.info("发送成功!");
                logger.info("开始推送微信");
                String firstData = "您好，有一份在" + stationName + "进行的" + serviceStr + "的常规服务报告,需要" + departmentStr + "跟进。";
                for (User manageUser : telephoneUser.keySet()) {
                    wechatService.pushWechatMessage(manageUser, "jUjiQshE94Fr5PhYigl0aLU_OZeybefechS7Oz1v4x4", Constants.WECHAT_PUSH_URL, firstData,
                            "请尽快查看并处理！", "24小时无人认领报告", realName, stationReport.getUpdateTimeStr(), "", "");
                }
                logger.info("微信推送成功!");
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("发送失败!");
            }
        }

    }

    /**
     * 管理员设置的时间，用于定时判断接受之后没有处理的报告
     */
    @Scheduled(cron = "0 0 * * * ?")//每个小时执行一次
    public void sendAutoMessage() {
        logger.info("定时任务-开始常规报告超时处理");
        AutoMessageTime autoMessageTime = autoMessageTimeRepository.findOne(1L);
        if (autoMessageTime == null) {
            return;
        }
        Long dayNum = autoMessageTime.getDayNum();
        Long time = dayNum * 60 * 60 * 24 * 1000;
        Long nowTime = System.currentTimeMillis();
        QReportRedDot qReportRedDot = QReportRedDot.reportRedDot;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qReportRedDot.deleted.eq(false));
        builder.and(qReportRedDot.enabled.eq(true));
        builder.and(qReportRedDot.type.ne("该事项已完成"));
        builder.and(qReportRedDot.type.ne("需其他部门后续跟进"));
        builder.and(qReportRedDot.isAutoMessage.eq(0));
        List<ReportRedDot> reportRedDotList = (List<ReportRedDot>) reportRedDotRepository.findAll(builder);
        Map<Long, ReportRedDot> redDotIntegerMap = new HashMap<>();
        logger.info("定时任务-常规报告超时处理：一共查出{}份", reportRedDotList.size());
        for (ReportRedDot redDot : reportRedDotList) {
            Long reportTime = redDot.getUpdateTime().getTime();
            if ((nowTime - reportTime) < time) {
                continue;
            }
            redDotIntegerMap.put(redDot.getStationReport().getId(), redDot);
        }
        logger.info("定时任务-常规报告超时处理：超时的有{}份", redDotIntegerMap.size());
        for (Map.Entry<Long, ReportRedDot> reportId : redDotIntegerMap.entrySet()) {
            logger.info("定时任务-常规报告超时处理：对应的ReportRedDot Id为：{}", reportId.getKey());
            ReportRedDot redDot = reportId.getValue();
            StationReport stationReport = redDot.getStationReport();
            StringBuffer stringBuffer = new StringBuffer("");
            if (stationReport != null && StringUtils.isNotEmpty(stationReport.getServiceTypAnswerIds())) {
                String[] ids = stationReport.getServiceTypAnswerIds().split(",");
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        if (id.equals("191")) {
                            stringBuffer.append("漆星服务");
                            break;
                        } else {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                            if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                stringBuffer.append(answerOption.getName() + ",");
                            }
                        }
                    }
                }
            }
            Station station = stationReport.getStation();
            User redDotUser = redDot.getUser();
            String redDotUserName = "";
            if (redDot != null && null != redDotUser) {
                UserProfile userProfile = userProfileRepository.findByUserId(redDotUser.getId());
                if (null != userProfile) {
                    redDotUserName = userProfile.getRealName();
                } else {
                    continue;
                }
            } else {
                continue;
            }

            //获取管理员手机号
            AdminUserVo adminUserVo = userAdminService.getAdminUser();
            List<User> oppenIdUser = adminUserVo.getUserList();
            String serviceStr = stringBuffer.toString();
            if (!serviceStr.equals("漆星服务")) {
                serviceStr = serviceStr.substring(0, serviceStr.length() - 1);
            }
//            String telephoneStr = "18521538142,13761230730";
//            logger.info("发送的号码为：" + telephoneStr);
            logger.info("外勤人员为：" + redDotUserName);
            logger.info("维修站为：" + station.getName());
            logger.info("服务目标为：" + stringBuffer.toString());
            try {
//                aliSmsProvider.sendAutoMessage(telephoneStr, redDotUserName, station.getName(), serviceStr, dayNum);
                String firstData = "您好，" + redDotUserName + "领取的在" + station.getName() + "进行的" + stringBuffer.toString() + "已超过" + dayNum + "天未处理完成。";
                String nowTimeStr = simpleDateFormat.format(new Date());
                String keyWord3 = "在" + station.getName() + "进行的" + serviceStr;
                for (User user1 : oppenIdUser) {
                    wechatService.pushWechatMessage(user1, "sPL21Oj3MEQjKjGS-GDHQFC_L5Ngiz4zLxsRcYEXAcc", Constants.WECHAT_PUSH_URL, firstData,
                            "请尽快查看并处理", redDotUserName, nowTimeStr, keyWord3, "", "");
                }
                redDot.setIsAutoMessage(1);
                reportRedDotRepository.save(redDot);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 定时检查领取的投诉报告是否超时
     */
    @Scheduled(cron = "0 0/5 * * * ?")//每300秒执行一次
    public void timeComplaintReport() {
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));
        booleanBuilder.and(qComplaintReport.audit.eq(true));
//        booleanBuilder.and(qComplaintReport.receive.eq(false));
        booleanBuilder.and(qComplaintReport.sendMessage.eq(false));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.COMPLETE));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.STOP));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.TIME_OUT));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.OTHER_FOLLOW));
        booleanBuilder.and(qComplaintReport.reportStatus.ne(Constants.FOLLOW));
        booleanBuilder.and(qComplaintReport.auditFalse.eq(false));
        booleanBuilder.and(qComplaintReport.back.eq(false));
        List<ComplaintReport> complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(booleanBuilder);
        for (ComplaintReport report : complaintReportList) {
            ComplaintTimeResponse timeResponse = complaintTimeService.getComplaintTime(report);
            if (timeResponse.getRemainingTime().indexOf("超") != -1) {
                report.setSendMessage(true);
                report.setReceive(false);
                report.setBack(true);
                report.setTimeOut(true);
                report.setReportStatus(Constants.TIME_OUT);
                complaintReportRepository.save(report);
                //将超时的投诉解决方案ID存入数据库
                if (null != report.getSolutionId()) {
                    ComplaintSolutionReport complaintSolutionReport = complaintSolutionReportRepository.findOne(report.getSolutionId());
                    if (null != complaintSolutionReport) {
                        ComplaintSolutionTimeOut complaintSolutionTimeOut = new ComplaintSolutionTimeOut();
                        complaintSolutionTimeOut.setSolutionComplaintId(report.getSolutionId());
                        complaintSolutionTimeOutRepository.save(complaintSolutionTimeOut);
                    }
                }
                //记录此人对此报告记录
                if (null != report.getFollowUser()) {
                    complaintUserService.updateComplaintUser(report.getFollowUser(), report);
                    BooleanBuilder builder = new BooleanBuilder();
                    QComplaintUser qComplaintUser = QComplaintUser.complaintUser;
                    builder.and(qComplaintUser.deleted.eq(false));
                    builder.and(qComplaintUser.enabled.eq(true));
                    builder.and(qComplaintUser.complaintReport.id.eq(report.getId()));
                    builder.and(qComplaintUser.user.id.eq(report.getFollowUser().getId()));
                    ComplaintUser complaintUser = complaintUserRepository.findOne(builder);
                    complaintUser.setTimeOut(false);
                    complaintUserRepository.save(complaintUser);
                }
                //记录日志
                ComplaintReportLog complaintReportLog = new ComplaintReportLog();
                if (null == report.getFollowUser()) {
                    complaintReportLog.setUserName("");
                    complaintReportLog.setReportStatus("待领取超时");
                } else {
                    UserProfile userProfile = userProfileRepository.findByUserId(report.getFollowUser().getId());
                    complaintReportLog.setUserName(userProfile.getRealName());
                    complaintReportLog.setUser(report.getFollowUser());
                    complaintReportLog.setReportStatus("处理投诉超时");
                }
                complaintReportLog.setOrange(true);
                complaintReportLog.setTime(new SimpleDateFormat(Constants.DATE_TIME_FORMAT).format(new Date()));
                complaintReportLog.setComplaintReportId(report.getId());
                complaintReportLogRepository.save(complaintReportLog);
                sendOutMessage(report);
            }
        }
    }

    /**
     * 超时通知
     *
     * @param complaintReport
     */
    private void sendOutMessage(ComplaintReport complaintReport) {
        //获取管理员手机号
        AdminUserVo adminUserVo = userAdminService.getAdminUser();
        List<User> oppenIdUser = adminUserVo.getUserList();
        String customer = complaintReportService.getComplaintReportCustomer(complaintReport.getId());
        List<User> techUser = new ArrayList<>();
        try {
            if (null != complaintReport.getLeader() && complaintReport.getLeader() != 0) {
                User user = userRepository.findOne(complaintReport.getLeader());
                if (null != user) {
                    techUser.add(user);
                }
            } else if (null != complaintReport.getNeedUserList()) {
                for (Long userId : complaintReport.getNeedUserList()) {
                    User user = userRepository.findOne(userId);
                    if (null != user) {
                        techUser.add(user);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TimeOutErrorMsg timeOutErrorMsg = new TimeOutErrorMsg();
            timeOutErrorMsg.setErrorMsg("异常：" + ExceptionUtil.getErrorInfoFromException(e));
            timeOutErrorMsgRepository.save(timeOutErrorMsg);
        }

        String createUser = getDepartmentNameForSendService.getUserDepartmentName(complaintReport.getUser());
        String firstStr = "您好，" + createUser + "在" + complaintReport.getCreationTimeStr() + "提交的"
                + customer + "的投诉报告状态已变更";
        String auditTimeStr = simpleDateFormat.format(complaintReport.getAuditTime());
        try {
            for (User user1 : oppenIdUser) {
                wechatService.pushWechatMessage(user1, "K8RDODMnerc2Orj7gbgTYKbalKDRqrJNyX6-s46OUc8", Constants.WECHAT_PUSH_URL, firstStr,
                        "该报告已超过领取和处理时效，请尽快处理！", "超时", auditTimeStr, "", "", "");
            }
            for (User user1 : techUser) {
                wechatService.pushWechatMessage(user1, "K8RDODMnerc2Orj7gbgTYKbalKDRqrJNyX6-s46OUc8", Constants.WECHAT_PUSH_URL, firstStr,
                        "该报告已超过领取和处理时效，已返回给管理员处理，请知悉。", "超时", auditTimeStr, "", "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TimeOutErrorMsg timeOutErrorMsg = new TimeOutErrorMsg();
            timeOutErrorMsg.setErrorMsg("超时：" + ExceptionUtil.getErrorInfoFromException(e));
            timeOutErrorMsgRepository.save(timeOutErrorMsg);
        }
    }

    /**
     * 定时检查自行跟进报告的预计时间是否超时
     */
    @Scheduled(cron = "0/60 * *  * * ? ")//每60秒执行一次
    public void checkoutscheduledTime() {
        logger.info("开始执行定时检查预计时间");
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QComplaintReport qComplaintReport = QComplaintReport.complaintReport;
        booleanBuilder.and(qComplaintReport.deleted.eq(false));
        booleanBuilder.and(qComplaintReport.enabled.eq(true));
        booleanBuilder.and(qComplaintReport.audit.eq(true));
        booleanBuilder.and(qComplaintReport.receive.eq(true));
        booleanBuilder.and(qComplaintReport.sendScheduledTimeMessage.eq(false));
        booleanBuilder.and(qComplaintReport.reportStatus.eq(Constants.FOLLOW));
        booleanBuilder.and(qComplaintReport.auditFalse.eq(false));
//        booleanBuilder.and(qComplaintReport.scheduledTime.isNotNull());
        List<ComplaintReport> complaintReportList = (List<ComplaintReport>) complaintReportRepository.findAll(booleanBuilder);
        logger.info("查出的预计时间报告有{}份", complaintReportList.size());
        Long nowTime = System.currentTimeMillis();
        for (ComplaintReport report : complaintReportList) {
            Long scheduledTime = report.getScheduledTime().getTime();
            logger.info("计算出的时间为{}", scheduledTime - nowTime);
            if ((scheduledTime - nowTime) < 0) {
                logger.info("报告ID为 {} 超过了预计时间", report.getId());
                report.setSendScheduledTimeMessage(true);
                complaintReportRepository.save(report);
                sendScheduledTimeMessage(report);
            }
        }
    }


    private void sendScheduledTimeMessage(ComplaintReport complaintReport) {
        //获取管理员手机号
        AdminUserVo adminUserVo = userAdminService.getAdminUser();
        StringBuilder telephoneStr = adminUserVo.getTelephoneStr();
        List<User> oppenIdUser = adminUserVo.getUserList();
        telephoneStr.append(complaintReport.getFollowUser().getUsername());
        String customer = complaintReportService.getComplaintReportCustomer(complaintReport.getId());
        ComplaintSolutionReport solutionReport = complaintSolutionReportRepository.findOne(complaintReport.getComplaintSolutionId());
        String submitTime = complaintReport.getUpdateTimeStr();
        if (null != solutionReport) {
            submitTime = solutionReport.getCreationTimeStr();
        }
        try {
            String createUser = getDepartmentNameForSendService.getUserDepartmentName(complaintReport.getUser());
            String scheduledTimeStr = simpleDateFormat.format(complaintReport.getScheduledTime());
            String first = "您好，" + createUser + "在" + submitTime + "提交的" + customer + "的投诉报告已到达预计完成时间。";
            for (User user1 : oppenIdUser) {
                wechatService.pushWechatMessage(user1, "Ujk2bjdBKx3vU1IjSH3OyD84rgF0Hz-oU2Ds564DW2I", Constants.WECHAT_PUSH_URL, first,
                        "该报告已到达预计完成时间，请尽快登录漆星服务系统进行处理。", "已到达预计完成时间", scheduledTimeStr, "", "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TimeOutErrorMsg timeOutErrorMsg = new TimeOutErrorMsg();
            timeOutErrorMsg.setErrorMsg("预计超时：" + ExceptionUtil.getErrorInfoFromException(e));
            timeOutErrorMsgRepository.save(timeOutErrorMsg);
        }
    }


    Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
}
